<!--hmc 推送商品信息组件-->
<template>
  <div class="container">
     <p class="font20 color333">执行动作-推送商品信息</p>
    <div class="stepset mb30">
      <ul>
        <li :class="{'active':active>=1}">
          <span>1</span>
          <p>选择商品</p>
        </li>
        <li :class="{'active':active>=2}">
          <span>2</span>
          <p>选择触达方式</p>
        </li>
      </ul>
    </div>
    <div v-show="active==1">
      <el-form :inline="true" :model="goodsForm" size="mini" ref="goodsForm">
        <el-form-item label="商品编码：" prop="thirdSpuId" class="mb20 noMarginRight">
          <el-input class="w194" clearable v-model="goodsForm.thirdSpuId" placeholder="输入商品编码" maxlength="80" size="mini" />
        </el-form-item>
        <el-form-item  label="商品名称：" prop="goodsName" class="w178 mt30">
          <el-input  class="w194" clearable v-model="goodsForm.goodsName" placeholder="输入商品名称"  maxlength="80" size="mini" />
        </el-form-item>
        <el-form-item class="mb20 noMarginRight">
          <el-button class="resetButton"   icon="el-icon-refresh" @click="resetFormSpu('goodsForm')">重置</el-button>
          <el-button class="searchButton"  icon="el-icon-search" @click="getSpuPage">搜索</el-button>       
      </el-form-item>
      </el-form>
      
      <el-table :data="tableData" class="mb20" v-loading="loading">
        <el-table-column label="商品编码" prop="thirdSpuId"  width="280">
          <template slot-scope="scope">
            <el-radio v-model="values" :label="scope.row.thirdSpuId" @change.native="getGoodsId(scope.$index,scope.row)"></el-radio>
          </template>
        </el-table-column>
        <el-table-column align="center" label="商品名称" prop="goodsName"></el-table-column>
        <el-table-column align="center" label="当前状态" prop="goodsStatus">
          <template slot-scope="scope">
            <span v-if="scope.row.goodsStatus ==0 ">预审核</span>
            <span v-else-if="scope.row.goodsStatus == 1">待审核</span>
            <span v-else-if="scope.row.goodsStatus == 2">审核通过</span>
            <span v-else-if="scope.row.goodsStatus == 3">审核不通过</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" v-if="scope.row.thirdSpuId !=sendGoodsForm.goodsId" @click.native="selectGoods(scope.row)">选择</el-button>
            <el-button type="text"  v-else-if="scope.row.thirdSpuId ==sendGoodsForm.goodsId" disabled>已选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页栏-->
      <div class="toolbar t_r mb60" v-if="tableData.length > 0">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="tableDataSizeChange"
          @current-change="tableDataCurrentChange"
          :current-page="goodsForm.start"
          :page-size="goodsForm.limit"
          :total="tableTotal"
          :page-sizes="[5, 10, 15, 20]"
        ></el-pagination>
      </div>
    </div>

    <div v-show="active==2">
      <div class="flex mt30 mb40">
        <span class="font16 color333 turnInlineBlock h40 lh40">选择触达方式：</span>
        <el-checkbox-group v-model="checkList">
          <el-checkbox label="1" border class="el-checkbox-padding">短信</el-checkbox>
          <el-checkbox label="3" border class="el-checkbox-padding">邮件</el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="tab-container ">
        <el-tabs v-model="activeName" ref="tabs">
          <el-tab-pane v-for="item in tabList" :key="item.key" :label="item.label" :name="item.key"></el-tab-pane>
        </el-tabs>
      </div>
      <div v-show="activeName=='1' && this.checkList.includes('1')">
        <el-form :model="sendGoodsForm" size="mini" ref="sendGoodsForm" >
          <el-form-item label="短信模板："  :required="true" :show-message="false" class="mb30">
            <el-select class="w495 mr20 turnBlock f_l" v-model="smsTemplate" filterable placeholder="选择短信模板" size="mini"  @change="templateSelectSms">
              <el-option v-for="item in smsTemplateList" :key="item.thirdTemplateId" :label="item.templateName" :value="item"></el-option>
            </el-select>
            <el-button class="cancelButton mr20 turnBlock f_l" @click="refreshTemplate">刷新</el-button>
            <el-button class="searchButton noMarginLeft turnBlock f_l" @click="addTemplateLink">模板管理</el-button>
          </el-form-item>
          <el-form-item label="可选参数：" prop="value" class="mb30" label-width="91px">
            <el-button class="copyBtn mr20" :data-clipboard-text="sendGoodsForm.goodsName" @click="copyGoodsName" icon="el-icon-document-copy">商品名称</el-button>
            <span class="desc">*操作说明：点击复制相关参数，可粘贴至内容中</span>
          </el-form-item>
          <el-form-item label="短信内容："  :required="true" :show-message="false" class=" mb30 txt">
            <div class="w706 flex" v-html="smsContent">
              
            </div>
          </el-form-item>
          <el-form-item label="测试发送：" prop="value" class="flex phone labelMarginLeft5 mb60">
            <el-input class="w495 mr20" clearable v-model="sendGoodsForm.smsJson.testReceiver" placeholder="输入测试发送手机号" maxlength="11"  oninput="value=value.replace( /[^\d]/g,'')"></el-input>
            <el-button class="searchButton" @click="sendTestMessage(1)">发送</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-show="activeName=='3' && this.checkList.includes('3')">
        <el-form :model="sendGoodsForm" size="mini" ref="sendGoodsForm">
          <el-form-item label="邮件模板：" class=" mb30" :required="true" :show-message="false">
            <el-select class="w605 mr20 turnBlock f_l" v-model="mailTemplate" filterable placeholder="选择邮件模板"  size="mini" @change="templateSelectMail">
              <el-option v-for="item in mailTemplateList" :key="item.thirdTemplateId" :label="item.templateName" :value="item"></el-option>
            </el-select>
            <el-button class="cancelButton mr20 turnBlock f_l" @click="refreshTemplate">刷新</el-button>
            <el-button class="searchButton noMarginLeft turnBlock f_l" @click="addTemplateLink">模板管理</el-button>
          </el-form-item>
          <el-form-item label="可选参数：" prop="value" class="mb30" label-width="91px">
            <el-button icon="el-icon-document-copy" class="copyBtn mr20" :data-clipboard-text="sendGoodsForm.goodsName" @click="copyGoodsName" >商品名称</el-button>
            <span class="desc">*操作说明：点击复制相关参数，可粘贴至内容中</span>
          </el-form-item>
          <el-form-item label="邮件标题："  :required="true" :show-message="false" class="mb30">
            <el-input clearable v-model="sendGoodsForm.mailJson.mailTitle" placeholder="请输入邮件标题" maxlength="80" class="w605"></el-input>
          </el-form-item>
          <el-form-item label="邮件内容：" class=" mb30 txt" :required="true" :show-message="false" >
            <div class="w706 flex mr20 f_l" v-html="mailContent">

            </div>
            <el-button class="searchButton turnBlock f_l" @click="preview()">预览</el-button>
          </el-form-item>
          <el-form-item label="测试发送：" prop="testReceiver" class="mb60 flex phone labelMarginLeft5">
            <el-input class="w738 mr20" clearable v-model="sendGoodsForm.mailJson.testReceiver" placeholder="输入测试邮箱" maxlength="80"></el-input>
            <el-button class="searchButton" @click="sendTestMessage(3)">发送</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="save t_c mt30">
      <el-button class="cancelButton mr60" v-if="active == 1" @click="handleClose()">取消</el-button>
      <el-button class="searchButton" v-if="active == 1" @click="next">下一步</el-button>
      <el-button class="cancelButton mr60" v-if="active == 2" @click="active=1">上一步</el-button>
      <el-button class="searchButton" v-if="active == 2" @click="saveSendGoods">确认</el-button>
    </div>

    <el-dialog title="编辑"  :visible.sync="editorDialogVisible" width="50%" :before-close="editorDialogClose" center append-to-body :close-on-click-modal="false">
      <el-form :model="mailParamsForm" size="mini" ref="mailParamsForm">
        
        <el-upload class="avatar-uploader" :action="imgUpload" multiple :on-success="uploadSuccess" :show-file-list="false"></el-upload>
        <el-form-item label="编辑内容：" prop="params" label-width="100px" style="margin-top: 2px;" required>
          <quill-editor ref="sendGoodsEditor" v-model="mailParamsForm.params" style="height: 300px;margin-bottom: 45px;margin-top: 10px;" :options="editorOption"></quill-editor>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editorDialogVisible = false" class="cancelButton mr60">取 消</el-button>
        <el-button type="primary" @click="confirmParams" class="searchButton">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="预览"  :visible.sync="previewDialogVisible" width="50%" :before-close="previewDialogClose" center append-to-body :close-on-click-modal="false">
      <div>
        <h2 style="text-align: center; margin-top: 10px;">{{this.sendGoodsForm.mailJson.mailTitle}}</h2>
        <div style="margin: 10px 30px 30px 30px;" v-html="this.previewContent"></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false" class="searchButton">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

import Clipboard from 'clipboard';
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { isEmail,isMobile } from "@/utils/validate";
//富文本工具栏
var toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],

  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
  [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
  [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
  [{ 'direction': 'rtl' }],                         // text direction

  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
  [{ 'font': [] }],
  ['link', 'image'],
  [{ 'align': [] }],

  ['clean']                                         // remove formatting button
];
// 自动化营销-----推送商品信息组件
export default {
  name: "goods",
  components: {
    Clipboard,
    quillEditor,
  },
  data() {
    return {
      
      imgUpload: this.utils.imghost,
      editorOption: {
        theme: 'snow',
        boundary: document.body,
        modules: {
          toolbar: {
            container: toolbarOptions,//工具栏
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            }
          },
        },
        placeholder: '请输入参数内容',
        readOnly: false
      }, // 富文本初始化
      editorDialogVisible: false,
      mailParamsForm:{
        params:'',
        key:'', // 参数名称
      },
      checkList: ["1", "3"],
      tabList: [ { label: "短信", key: "1" }, { label: "邮件", key: "3" } ],
      active: 1, //初始选中
      activeName: "1",
      //商品
      tableData: [],
      goodsForm: {
        thirdSpuId:'',
        goodsName:'',
        start: 1,
        limit: 10,
      },
      smsTemplateList: [],//短信模版
      mailTemplateList: [],//邮件模版
      smsTemplate:"",
      mailTemplate:"",
      values:"",
      sendGoodsForm:{
        goodsId:"",
        goodsName:"",
        smsJson:{
          params:{

          },
          previewContent:"",
          templateName:"",
          testReceiver:""
        },
        mailJson:{
          mailTitle:"",
          params:{
            
          },
          previewContent:"",
          templateName:"",
          testReceiver:""
        },
      },
      //短信模版内容
      smsContent: "",
      smsParams:[],
      smsTemplateContent:"",
      //邮件模版内容
      mailContent: "",
      mailParams:[],
      previewContent:"",
      templateContent:"",
      previewDialogVisible: false,//邮件预览弹窗
      smsParamFlag:null,
    };
  },
  props: {
    id:Number,
    nodeInfo: {
      type: Object,
    },
    journeyId: {
      type: String,
      default: '',
    },
    loading: false,
  },

  methods: {

    //子关闭 标签选择弹框
    handleClose() {
      this.$emit("handleClose", false);
    },
    /**
     * 获取spu列表
     */
    getSpuPage(){
      this.loading = true;
      var that = this;
      // this.utils.request.getPageSpuList(this.goodsForm,res=>{
      //   if(res.code == '0000'){
      //       that.tableData = res.data.rows;
      //       that.tableTotal = res.data.total;
      //     }else{
      //       that.tableData = [];
      //       that.tableTotal = 0;
      //     }
      //   that.loading = false;
      // })
      
      this.goodsForm.status = 2;
      this.utils.request.queryPageProductManagement(this.goodsForm,res=>{
        if(res.code == '0000'){
            that.tableData = res.data.rows;
            let data = [];
            that.tableData.forEach(item => {
              data.push({
                thirdSpuId: item.code,
                goodsName: item.chineseName,
                goodsStatus: item.status,
                id: item.id
              });
            });
            that.tableData = data;
            that.tableTotal = res.data.total;
          }else{
            that.tableData = [];
            that.tableTotal = 0;
          }
        that.loading = false;
      });
    },
    
    /**
     * 重置查询
     */
    resetFormSpu(formName) {

      //需要校验的keys
			let keys = ["thirdSpuId","goodsName"]
			//调用校验
			let  boo = this.seachTableUtils.checkFromIsNull(this.goodsForm,keys)
			if(!boo){
				return;
      }
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
        this.getSpuPage();
      }
    },
    
    /**
     * 每页条数改变触发
     */
    tableDataSizeChange(val){
      this.goodsForm.limit = val;
      this.goodsForm.start = 1;
      this.getSpuPage();
    },
    /**
     * 换页刷新
     */
    tableDataCurrentChange(val){
      this.goodsForm.start = val;
      this.getSpuPage();
    },

    /**
     * 选择商品
     */
    selectGoods(row){
      this.values = row.thirdSpuId;
      this.sendGoodsForm.goodsId = row.thirdSpuId;
      this.sendGoodsForm.goodsName = row.goodsName;
    },
    getGoodsId(index,row){
      this.values = row.thirdSpuId;
      this.sendGoodsForm.goodsId = row.thirdSpuId
    },
    /**
     * 下一步
     */
    next(){
      if(this.sendGoodsForm.goodsId==""){
        this.$message({message: "请选择商品", type: "error"});
        return false;
      }
      this.active=2;
    },
    /**
     * 保存推送商品
     */
    saveSendGoods(){
      let that = this;
      //判断必填项
      if(this.checkList.length < 1){
        this.$message({"type":"warning",message:"请选择触达方式"})
        return false;
      }

      //判断短信参数
      if(this.checkList.includes("1")){
        if(this.sendGoodsForm.smsJson.tempId =="" || this.sendGoodsForm.smsJson.tempId == null){
          this.$message({message:"请选择短信模版",type:"error"})
          return false;
        }
        //判断参数是否全部输入
        if(that.smsParams.length > 0 ){
          for(var i=0;i<that.smsParams.length;i++){
            var key = that.smsParams[i];
            this.sendGoodsForm.smsJson.params[key] = document.getElementById(key).value;
            if(this.sendGoodsForm.smsJson.params[key]==null || this.sendGoodsForm.smsJson.params[key]=='' ){
              that.$message({ message: "请输入短信内容第"+ Number(i+1)+"个参数", type: "error" });
              return false;
            }
          }
        }
        if(this.sendGoodsForm.smsJson.testReceiver){
          if(!isMobile(this.sendGoodsForm.smsJson.testReceiver)){
            this.$message({message:"请输入正确的手机号", type:"error"});
            this.sendGoodsForm.smsJson.testReceiver = "";
            return false;
          }
        }
        
        //短信预览数据组装
        var paramList = this.smsTemplateContent.match(/\$\{[^}]+\}/g);
        var content = this.smsTemplateContent;
        if(paramList != null && paramList.length > 0){
          for(var i=0;i<paramList.length;i++){
            var key = paramList[i].replace("${","").replace("}","");
            content= content.replace(paramList[i],this.sendGoodsForm.smsJson.params[key]);
          }
        }
        this.sendGoodsForm.smsJson.previewContent = content;
      }
      //判断邮件参数
      if(this.checkList.includes("3")){
        if(this.sendGoodsForm.mailJson.tempId =="" || this.sendGoodsForm.mailJson.tempId == null){
          this.$message({message:"请选择邮件模版",type:"error"})
          return false;
        }
        if(this.sendGoodsForm.mailJson.mailTitle =="" || this.sendGoodsForm.mailJson.mailTitle == null){
          this.$message({message:"请输入邮件标题",type:"error"})
          return false;
        }
        //判断参数是否全部输入
        if(that.mailParams.length > 0 ){
          for(var i=0;i<that.mailParams.length;i++){
            var key = that.mailParams[i];
            if(this.sendGoodsForm.mailJson.params[key]==null || this.sendGoodsForm.mailJson.params[key]=='' ){
              that.$message({ message: "请输入邮件内容第"+ Number(i+1)+"个参数", type: "error" });
              return false;
            }
          }
        }
        if(this.sendGoodsForm.mailJson.testReceiver){
          if(!isEmail(this.sendGoodsForm.mailJson.testReceiver)){
            this.$message({message:"请输入正确的邮箱", type:"error"});
            this.sendGoodsForm.mailJson.testReceiver = "";
            return false;
          }
        }
        //邮件预览数据组装
        var paramList = this.templateContent.match(/\$\{[^}]+\}/g);
        var content = this.previewContent;
        if(paramList != null && paramList.length > 0){
          for(var i=0;i<paramList.length;i++){
            var key = paramList[i].replace("${","").replace("}","");
            content= content.replace(paramList[i],this.sendGoodsForm.mailJson.params[key]);

          }
        }
        this.sendGoodsForm.mailJson.previewContent = content;
      }
      
      //调用接口保存数据
      let branchNodeInfo = {
        nodeTemplateCode: this.nodeInfo.templateCode,
        nodeTemplateId: this.nodeInfo.id,
        id: this.nodeInfo.nodeId,
      }
      this.sendGoodsForm.reachType = this.checkList.join();
      branchNodeInfo.nodeVariable = this.sendGoodsForm;
      this.utils.request.updateBranchNode(branchNodeInfo,res=>{
          if(res.code == '0000'){
            that.$message({message:"保存成功",type:"success"})
            that.$emit("saveLabelData",{nodeName:this.sendGoodsForm.goodsName});
            that.$emit("handleClose", false);
          }
      })
    },
    
    /**
     * 查询短信邮件模板
     */
    tTempalteListAll(){
      //查询短信
      this.utils.request.tTempalteListAll({status: 1, templateType: 1},res=>{
          if(res.code == '0000'){
            this.smsTemplateList = res.data
            this.queryInfo();
          }else{
            this.smsTemplateList = []
          }
      })
      //查询邮件
      this.utils.request.tTempalteListAll({status: 1, templateType: 2},res=>{
          if(res.code == '0000'){
            this.mailTemplateList = res.data
            this.queryInfo();
          }else{
            this.mailTemplateList = []
          }
      })
    },
    
    /**
     * 复制商品名称
     */
    copyGoodsName() {
      var clipboard = new Clipboard(".copyBtn");
      
      clipboard.on("success", e => {
        this.$message({message: "复制成功", type: "success"});
        // 释放内存
        clipboard.destroy();
        //复制成功后获取输入框光标赋值
        if(this.smsParamFlag && this.smsParamFlag != null && e.text ){
          var myField = document.getElementById(this.smsParamFlag);
          var myValue = e.text;
          if (myField.selectionStart || myField.selectionStart == '0') {
            var startPos = myField.selectionStart;
            var endPos = myField.selectionEnd;
            var restoreTop = myField.scrollTop;
            myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
            if (restoreTop > 0) {
            myField.scrollTop = restoreTop;
            }
            myField.focus();
            myField.selectionStart = startPos + myValue.length;
            myField.selectionEnd = startPos + myValue.length;
            }
          else {
            myField.value += myValue;
            myField.focus();
          }
        }else{
          this.smsParamFlag = null;
        }
      });
      clipboard.on("error", e => {
        // 不支持复制
        this.$message({message: "该浏览器不支持自动复制 ", type: "error"});
        // 释放内存
        clipboard.destroy();
      });
    },

    /**
     * 校验手机正确性
     */
    checkTestPhone(vue){
      if(!isMobile(vue)){
        this.$message({message:"请输入正确的手机号", type:"error"});
        this.sendGoodsForm.smsJson.testReceiver = "";
        return false;
      }
    },

    /**
     * 校验邮箱正确性
     */
    checkTestMail(vue){
      if(!isEmail(vue)){
        this.$message({message:"请输入正确的邮箱", type:"error"});
        this.sendGoodsForm.mailJson.testReceiver = "";
        return false;
      }
    },
    
    /**
     * 测试发送
     */
    sendTestMessage(type){
      let that = this;
      let params = {
        type: type,
      }
      if( type == 1 ){
        if(this.sendGoodsForm.smsJson.tempId =="" || this.sendGoodsForm.smsJson.tempId == null){
          this.$message({message:"请选择短信模版输入参数后进行测试发送",type:"error"})
          return false;
        }
        if( type == 1 && (that.sendGoodsForm.smsJson.testReceiver == null || that.sendGoodsForm.smsJson.testReceiver == '')){
          that.$message({message:"请输入测试手机号", type: "error"})
          return false;
        }
        if(!isMobile(that.sendGoodsForm.smsJson.testReceiver)){
          this.$message({message:"请输入正确的手机号", type:"error"});
          that.sendGoodsForm.smsJson.testReceiver = "";
          return false;
        }
        if(that.smsParams.length > 0){
          for(var i=0;i<that.smsParams.length;i++){
            var key = that.smsParams[i];
            this.sendGoodsForm.smsJson.params[key] = document.getElementById(key).value;
            if(this.sendGoodsForm.smsJson.params[key]==null || this.sendGoodsForm.smsJson.params[key]=='' ){
              that.$message({ message: "请输入短信内容第"+ Number(i+1)+"个参数", type: "error" });
              return false;
            }
          }
        }
        params = Object.assign(params, this.sendGoodsForm.smsJson);
      }else if( type == 3 ){
        
        if(this.sendGoodsForm.mailJson.tempId =="" || this.sendGoodsForm.mailJson.tempId == null){
          this.$message({message:"请选择邮件模版输入参数后进行测试发送",type:"error"})
          return false;
        }
        if(this.sendGoodsForm.mailJson.mailTitle =="" || this.sendGoodsForm.mailJson.mailTitle == null){
          this.$message({message:"请输入邮件标题",type:"error"})
          return false;
        }
        if( type == 3 && (that.sendGoodsForm.mailJson.testReceiver==null ||that.sendGoodsForm.mailJson.testReceiver == '')){
          that.$message({message:"请输入测试邮箱", type: "error"})
          return false;
        }
        if(!isEmail(that.sendGoodsForm.mailJson.testReceiver)){
          that.$message({message:"请输入正确的邮箱", type:"error"});
          that.sendGoodsForm.mailJson.testReceiver = "";
          return false;
        }
        if(that.mailParams.length > 0){
          for(var i=0;i<that.mailParams.length;i++){
            var key = that.mailParams[i];
            if(this.sendGoodsForm.mailJson.params[key]==null || this.sendGoodsForm.mailJson.params[key]=='' ){
              that.$message({ message: "请输入邮件内容第"+ Number(i+1)+"个参数", type: "error" });
              return false;
            }
          }
        }
        params = Object.assign(params, this.sendGoodsForm.mailJson);
      }
      this.utils.request.sendTestMessage(params, res => {
        if (res.code == "0000") {
          if(res.data.code == "0"){
            that.$message({ message: res.data.message, type: "success" });
          }else{
            that.$message({ message: res.data.message, type: "error" });
          }
        }
      });
    },
    /**
     * 短信模板选择
     */
    templateSelectSms(item){
      this.smsParamFlag = null;//清空短信模板动态标识
      this.smsTemplate = item.templateName;
      this.sendGoodsForm.smsJson.templateName = item.templateName;
      var content = item.templateContent;
      this.smsTemplateContent = item.templateContent;
      var textList = content.split(/\$\{[^}]+\}/);
      var paramList = content.match(/\$\{[^}]+\}/g);
      this.smsParams = [];
      this.sendGoodsForm.smsJson.params = {};
      if(paramList != null ){
        for(var i=0;i<paramList.length;i++){
          this.smsParams.push(paramList[i].replace("${","").replace("}",""));
          this.sendGoodsForm.smsJson.params[paramList[i].replace("${","").replace("}","")] = "";
          content= content.replace(paramList[i],'&nbsp;&nbsp;<textarea class="textareaParm" type="text" id="'+paramList[i].replace("${","").replace("}","")+'"></textarea>&nbsp;&nbsp;');
        }
      }
      this.sendGoodsForm.smsJson.tempId = item.thirdTemplateId;
      this.smsContent = content;
      //短信模板动态增加onfocus事件
      let that = this;
      $(document).ready(function(){
          $(function() {
            for(var i=0;i<paramList.length;i++){
              let j = i;
              let key = paramList[j].replace("${","").replace("}","");
              document.getElementById(key).onfocus = function(){
                that.smsParamFlag = key;
              }
            }
          });

      })
    },
    
    /**
     * 邮件模版选择
     */
    templateSelectMail(item){
      this.mailTemplate = item.templateName;
      this.sendGoodsForm.mailJson.mailTitle = item.templateName;
      this.sendGoodsForm.mailJson.templateName = item.templateName;
      var content = item.templateContent;
      this.templateContent = item.templateContent;
      this.previewContent = item.templateContent;
      var textList = content.split(/\$\{[^}]+\}/);
      var paramList = content.match(/\$\{[^}]+\}/g);
      this.mailParams = [];
      this.sendGoodsForm.mailJson.params = {};
      if(paramList != null ){
        for(var i=0;i<paramList.length;i++){
          this.mailParams.push(paramList[i].replace("${","").replace("}",""));
          this.sendGoodsForm.mailJson.params[paramList[i].replace("${","").replace("}","")] = "";
          content= content.replace(paramList[i],'&nbsp;&nbsp;<button class="buttonParm" type="button" onsubmit="return false" id="'+paramList[i].replace("${","").replace("}","")+i+'">编辑</button>&nbsp;&nbsp;');

        }
      }
      this.sendGoodsForm.mailJson.tempId = item.thirdTemplateId;
      this.mailContent = content;
      var mailParamsList = this.mailParams;
      //绑定按钮事件
      var that = this;
      $(document).ready(function(){
          $(function() {
            //jq事件
            for(var i=0;i<mailParamsList.length;i++){
              let j = i;
              let key = mailParamsList[j];
              document.getElementById(key+j).onclick = function(){
                that.editorDialogVisible = true;
                that.mailParamsForm.params = "";
                that.mailParamsForm.key = key;
                that.previewContent = item.templateContent;
                //设置value
                that.mailParamsForm.params = that.sendGoodsForm.mailJson.params[key]
              }
            }
          });
      
      })
    },
    
    /**
     * 富文本图片上传
     */
    uploadSuccess(res, file) {
      // 首先获取富文本编辑器的实例
      let quill = this.$refs.sendGoodsEditor.quill
      // 上传成功所执行
      if (res.code == "0000" && res.data !== null) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片res为服务器返回的数据
        quill.insertEmbed(length, 'image', res.data.imageUrl)
        // 光标移动至文本末端
        quill.setSelection(length + 1)
      } else {
        this.$message({message:"图片插入失败", type:"error" });
      }
    },
    /**
     * 确认弹窗数据保存——邮件参数
     */
    confirmParams(){
      if(this.mailParamsForm.params == null || this.mailParamsForm.params == '' ){
        this.$message({message:"请输入内容", type:"error" });
        return false;
      }
      var key = this.mailParamsForm.key;
      this.sendGoodsForm.mailJson.params[key] = this.mailParamsForm.params;
      this.editorDialogVisible = false;
    },
    /**
     * 邮件预览
     */
    preview(){
      if(this.sendGoodsForm.mailJson.tempId =="" || this.sendGoodsForm.mailJson.tempId == null){
        this.$message({message:"请选择邮件模版输入参数后预览",type:"error"})
        return false;
      }
      //判断参数是否全部输入
      var booFlag = false;
      for (const key in this.sendGoodsForm.mailJson.params) {
        const value = this.sendGoodsForm.mailJson.params[key];
        if(value == null ||  value == ''){
            booFlag = true;
            break;
        }
      }
      if(booFlag){
        this.$message({message:"请补充完参数后预览",type:"error"})
        return false;
      }
      //预览数据组装
      var paramList = this.templateContent.match(/\$\{[^}]+\}/g);
      var content = this.previewContent;
      for(var i=0;i<paramList.length;i++){
        var key = paramList[i].replace("${","").replace("}","");
        content= content.replace(paramList[i],this.sendGoodsForm.mailJson.params[key]);

      }
      this.previewContent = content;
      this.previewContent = this.previewContent.replace(/img/g,"img style='width:100%;height:100%'"); 
      this.previewDialogVisible = true;

    },
    /**
     * 邮件预览关闭
     */
    previewDialogClose(){
      this.previewDialogVisible = false;
    },

    /**
     * 邮件参数弹窗关闭
     */
    editorDialogClose(){
      this.editorDialogVisible = false;
    },
    /**
     * 数据回显
     */
    queryInfo(){
      let that = this;
      this.utils.request.getBranchNodeDetail({branchNodeId: this.nodeInfo.nodeId}, res=>{
        if(res.code == '0000'){
          if(res.data.nodeVariable != null || res.data.nodeVariable != ''){
              //回显数据
              let data = JSON.parse(res.data.nodeVariable);
              that.sendGoodsForm.goodsId = data.goodsId;
              that.values = data.goodsId;
              that.sendGoodsForm.goodsName  = data.goodsName;
              //回显reachType
              let reachType = data.reachType.split(",");
              that.checkList = reachType;
              if(reachType.includes("1")){
                //回显短信
                // this.sendCouponDataForm.smsJson = data.smsJson;
                let item = null;
                that.smsTemplateList.forEach(smsTemplate=>{
                  if(smsTemplate.thirdTemplateId == data.smsJson.tempId){
                    item = smsTemplate;
                  }
                })
                that.templateSelectSms(item);
                that.$nextTick(()=>{
                  //设置输入框值
                  if(that.smsParams.length > 0){
                    for(var i=0;i<this.smsParams.length;i++){
                      var key = this.smsParams[i];
                      document.getElementById(key).value = data.smsJson.params[key];
                    }
                  }
                })
                that.sendGoodsForm.smsJson = data.smsJson;
              }
              if(reachType.includes("3")){
                //回显邮件
                let item = null;
                that.mailTemplateList.forEach(mailTemplate=>{
                  if(mailTemplate.thirdTemplateId == data.mailJson.tempId){
                    item = mailTemplate;
                  }
                })
                // 默认选中
                that.templateSelectMail(item);
                that.sendGoodsForm.mailJson = data.mailJson;
              }
          }
        }
      })
    },

    /**
    /**
     * 刷新模版
     */
    refreshTemplate(){
      this.tTempalteListAll();
    },
    /**
     * 新增模版跳转
     */
    addTemplateLink(){
      this.$confirm('打开新页面时将刷新本页面，并清空本次编辑的数据，请先将流程保存为草稿', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push({path:"/pages/TemplateManagement/TemplateManagement"});
      }).catch(() => { });
    },
  },

  mounted() {
    this.getSpuPage();
    this.tTempalteListAll();
  },
  watch:{
    checkList: function(){
      if(!this.checkList.includes("1")){
        this.$refs.tabs.$children[0].$refs.tabs[0].style.display = 'none';
        this.activeName = "3";
      }else{
        this.$refs.tabs.$children[0].$refs.tabs[0].style.display = 'inline-block';
        this.activeName = "1";
      }
      if(!this.checkList.includes("3")){
        this.$refs.tabs.$children[0].$refs.tabs[1].style.display = 'none';
        this.activeName = "1";
      }else{
        this.$refs.tabs.$children[0].$refs.tabs[1].style.display = 'inline-block';
        this.activeName = "3";
      }
    }
  },
  created() {
    
  }
};
</script>
<style lang="scss" scoped>
.stepset {
  ul {
    width: 460px;
  }
  .flex {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
}
.el-checkbox {
  margin-right: 30px;
}
/deep/ .el-form {
  .txt {
    /deep/ .el-form-item {
      margin-top: 0px;
    }
    .flex {
      line-height: 3;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
    }
    .el-textarea {
      width: auto;
    }
  }
  .phone {
    .el-form-item__content {
      display: flex;
      justify-content: flex-start;
    }
  }
  
  .textareaParm{
    -webkit-appearance: none;
    background-color: #FFF;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: inherit;
    outline: 0;
    padding: 0 15px;
    -webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
  }
  .buttonParm{
    padding: 0 16px !important;
    border-radius: 4px;
    height: 32px !important;
    line-height: 32px !important;
    font-size: 14px !important;
    background: #FFF;
    border: 1px solid #DCDFE6;
    color: #606266;
    background: #66b1ff;
    border-color: #66b1ff;
    color: #FFF;
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    -webkit-appearance: none;
    text-align: center;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    outline: 0;
    margin: 0;
    -webkit-transition: .1s;
    transition: .1s;
    font-weight: 500;
    padding: 12px 20px;
    font-size: 14px;
    border-radius: 4px;
  }
}
.font20{
  font-size: 20px !important;
}
/deep/ .w194{
  width: 194px !important;
  .el-input__inner{
    width: 194px  !important;
  }
}
.noMarginRight{
  margin-right: 0 !important;
}
.labelMarginLeft5{
  /deep/ .el-form-item__label{
    margin-left: 10px;
  }
}
/deep/ .w495{
  width: 495px !important;
  .el-input__inner{
    width:495px !important;
  }
}
/deep/ .w605{
  width: 605px !important;
  .el-input__inner{
    width:605px !important;
  }
}
.noMarginLeft{
  margin-left: 0 !important;
}
/deep/ .copyBtn{
  border: 1px solid #0079DC !important;
  border-radius: 16px !important;
  background-color: #409EFF !important;
  color: #fff !important;
}
.mr10{
  margin-right: 10px !important;
}
.desc{
  color: #c4c4c4;
  font-size: 14px;
}
.w706{
  width: 706px !important;
}
.w738{
  width: 738px !important;
}
.h40{
  height: 40px !important;
}
.lh40{
  line-height: 40px !important;
}
</style>

